package com.example.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {


    private JacksonUtil(){

    }

    private static final ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER=new ObjectMapper();
    }


    public static ObjectMapper getObjectMapper(){
        return OBJECT_MAPPER;
    }

    private static  <T> T tryParse(Callable<T> parser)  {
        return tryParse(parser, JacksonException.class);
    }

    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check)  {
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                try {
                    throw new JsonParseException(var4.getMessage());
                } catch (JsonParseException e) {
                    throw new RuntimeException(e);
                }
            }

            throw new IllegalStateException(var4);
        }
    }


    public static String writeValueAsString(Object object)  {

            return JacksonUtil.tryParse(()->{
                return JacksonUtil.getObjectMapper().writeValueAsString(object);
            });
    }


    public static <T> T readValue(String str,Class<T> valueType)  {

        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(str,valueType);
        });
    }

    public static<T> T  readListValue(String str,Class<?> valueType){
        TypeFactory typeFactory = JacksonUtil.getObjectMapper().getTypeFactory();
        JavaType javaType = typeFactory.constructParametricType(List.class, valueType);

        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(str,javaType);
        });

    }





}
